﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MusicAcademy
{
    public partial class frmPersonFiles : Form
    {
        public int PersonID = -1;
        private string fileName = "", filename2 = "";
        private int recordID = -1;

        public frmPersonFiles()
        {
            InitializeComponent();
        }

        private void RefreshGrid()
        {
            fullPersonFileTableAdapter.Fill(musicAcademyDataSet.FullPersonFile, PersonID);
        }

        private bool isValid()
        {
            bool valid = true;
            if (PersonID== -1)
                valid = Globals.SetError(txtPerson);
            else
                Globals.SetValid(txtPerson);
            
            if (fileName == "")
                valid = Globals.SetError(btnOpenFile);
            else
                Globals.SetValid(btnOpenFile);

            return valid;
        }
        private void frmPersonFiles_Load(object sender, EventArgs e)
        {
            if (UserManager.HasAccess("frmPersonFiles", "View") == false)
            {
                MessageBox.Show("شما اجازه ی دیدن این فرم را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            // TODO: This line of code loads data into the 'musicAcademyDataSet.FileType' table. You can move, or remove it, as needed.
            this.fileTypeTableAdapter.Fill(this.musicAcademyDataSet.FileType);
            RefreshGrid();
            if (cmbFileType.Items.Count > 0)
                cmbFileType.SelectedIndex = 0;
        }

        private void btnSelectPerson_Click(object sender, EventArgs e)
        {
            ListOfPersons p = new ListOfPersons();
            p.PersonType = 0;
            if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PersonID = p.SelectedID;
                txtPerson.Text = p.FirstName + " " + p.LastName;
                RefreshGrid();
            }
        }

        private bool OpenFile()
        {
            string ext = fileName.Substring(fileName.LastIndexOf(".") + 1);
            btnOpenFile.Text = "انتخاب فایل : " + GetFileName(fileName);

            switch (ext.ToLower())
            {
                case "bmp":
                case "jpg":
                case "jpeg":
                case "gif":
                case "png":
                    try
                    {
                        pictureBox1.Image = Image.FromFile(fileName);
                        pictureBox1.Cursor = Cursors.Hand;
                        return true;
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("خطا در هنگام باز کردن فایل!");
                        pictureBox1.Cursor = Cursors.Hand;
                        pictureBox1.Image = Image.FromFile(Program.FilesPath + "UnknownFile.png");
                        return false;
                    }    
                default:
                    pictureBox1.Cursor = Cursors.Hand;
                    pictureBox1.Image = Image.FromFile(Program.FilesPath + "UnknownFile.png");
                    return false;
            }
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileName = openFileDialog1.FileName;
                OpenFile();
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try
            {
                if (fileName != "")
                    System.Diagnostics.Process.Start(fileName);
            }
            catch (Exception)
            {
                MessageBox.Show("خطا در هنگام باز کردن فایل !");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
            RefreshGrid();
        }

        private string GetFileName(string fname)
        {
            return fname.Substring(fname.LastIndexOf("\\") + 1);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            string fn = "";

            if (isValid() == false)
                return;

            fn = GetFileName(fileName);
            com.Connection = con;
            com.CommandType = CommandType.Text;

            if (recordID == -1)
            {
                if (UserManager.HasAccess("frmPersonFiles", "Insert") == false)
                {
                    MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                com.CommandText = "INSERT INTO PersonFile (personID, fileAddress, fileTypeID, description, creator, createDate) VALUES (@personID, @fileAddress, @fileTypeID, @description, @creator, @createDate); SELECT MAX(ID) AS R FROM PersonFile";
                com.Parameters.AddWithValue("@personID", PersonID);
                com.Parameters.AddWithValue("@fileAddress", "");
                com.Parameters.AddWithValue("@fileTypeID", cmbFileType.SelectedValue);
                com.Parameters.AddWithValue("@description", txtDescription.Text);
                com.Parameters.AddWithValue("@creator", Program.userID);
                com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());
                con.Open();
                dreader = com.ExecuteReader();
                dreader.Read();
                recordID = int.Parse(dreader["R"].ToString());
                dreader.Close();

                try
                {
                    System.IO.File.Copy(fileName, Program.FilesPath + recordID.ToString() + "-" + fn);
                }
                catch (Exception)
                {
                    MessageBox.Show("خطا در هنگام ذخیره فایل !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                com.Parameters.Clear();
                com.CommandText = "UPDATE PersonFile SET fileAddress=@fileAddress WHERE ID=@ID";
                com.Parameters.AddWithValue("@fileAddress", Program.FilesPath + recordID.ToString() + "-" + fn);
                com.Parameters.AddWithValue("@ID", recordID);
                com.ExecuteNonQuery();
                com.Parameters.Clear();

                con.Close();
                cmbFileType.SelectedIndex = 0;
                txtDescription.Text = "";
                recordID = -1;
                pictureBox1.Image = null;
                btnOpenFile.Text = "انتخاب فایل";
                btnSelectPerson.Enabled = true;
                fileName = "";
                filename2 = "";
                RefreshGrid();
            }
            else
            {
                if (UserManager.HasAccess("frmPersonFiles", "Update") == false)
                {
                    MessageBox.Show("شما اجازه ی ویرایش کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                
                try
                {
                    if (fileName != filename2)
                    {
                        if (System.IO.File.Exists(filename2))
                        {
                            pictureBox1.Image = null;
                            System.IO.File.Delete(filename2);
                        }
                    }
                }
                catch (Exception)
                {

                }
                try
                {
                    System.IO.File.Copy(fileName, Program.FilesPath + recordID.ToString() + "-" + fn);
                    filename2 = fileName;
                }
                catch (Exception)
                {
                    MessageBox.Show("خطا در هنگام ذخیره فایل !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                com.CommandText = "UPDATE PersonFile SET fileAddress=@fileAddress, fileTypeID=@fileTypeID, description=@description, lastEditor=@lastEditor, editDate=@editDate WHERE ID=@ID";
                com.Parameters.AddWithValue("@fileAddress", Program.FilesPath + recordID.ToString() + "-" + fn);
                com.Parameters.AddWithValue("@fileTypeID", cmbFileType.SelectedValue);
                com.Parameters.AddWithValue("@description", txtDescription.Text);
                com.Parameters.AddWithValue("@lastEditor", Program.userID);
                com.Parameters.AddWithValue("@editDate", Globals.Get10CharDate());
                com.Parameters.AddWithValue("@ID", recordID);
                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                cmbFileType.SelectedIndex = 0;
                txtDescription.Text = "";
                fileName = "";
                filename2 = "";
                recordID = -1;
                pictureBox1.Image = null;
                btnOpenFile.Text = "انتخاب فایل";
                btnSelectPerson.Enabled = true;
                RefreshGrid();
            }
            MessageBox.Show("ذخیره شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void grdPersonFile_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            Globals.SetValid(txtPerson);
            Globals.SetValid(btnOpenFile);

            recordID = Convert.ToInt32(grdPersonFile.Rows[e.RowIndex].Cells["ID"].Value);
            txtPerson.Text = grdPersonFile.Rows[e.RowIndex].Cells["FirstName"].Value.ToString() + " " + grdPersonFile.Rows[e.RowIndex].Cells["LastName"].Value.ToString();
            cmbFileType.SelectedValue = Convert.ToInt32(grdPersonFile.Rows[e.RowIndex].Cells["fileTypeID"].Value);
            fileName = grdPersonFile.Rows[e.RowIndex].Cells["fileAddress"].Value.ToString();
            filename2 = fileName;
            txtDescription.Text = grdPersonFile.Rows[e.RowIndex].Cells["description"].Value.ToString();
            btnSelectPerson.Enabled = false;
            btnDelete.Enabled = true;
            PersonID = Convert.ToInt32(grdPersonFile.Rows[e.RowIndex].Cells["_personID"].Value);
            OpenFile();
        }

        private void ClearForm()
        {
            txtPerson.Text = "";
            btnSelectPerson.Enabled = true;
            cmbFileType.SelectedIndex = 0;
            txtDescription.Text = "";
            btnOpenFile.Text = "انتخاب فایل";
            pictureBox1.Cursor = Cursors.Default;
            pictureBox1.Image = null;
            btnDelete.Enabled = false;
            recordID = -1;
            PersonID = -1;
            fileName = "";
            filename2 = "";
            Globals.SetValid(txtPerson);
            Globals.SetValid(btnOpenFile);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            if (UserManager.HasAccess("frmPersonFiles", "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (MessageBox.Show("آیا از حذف این رکورد اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                com.Connection = con;
                com.CommandType = CommandType.Text;

                com.CommandText = "DELETE FROM PersonFile WHERE ID=@ID;";
                com.Parameters.AddWithValue("@ID", recordID);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                ClearForm();
                RefreshGrid();
                MessageBox.Show("حذف شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}
